package com.example.myspringboot.service.vavrImpl;

import cn.hutool.core.util.RandomUtil;
import com.example.myspringboot.anno.Loggable;
import io.vavr.collection.List;
import io.vavr.concurrent.Future;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author cy
 * @date 2024/5/28
 */
@Service
public class AsynchronousExample {

    @Loggable
    public void asyncMethod() {
        // 创建一个包含多个REST API调用的列表
        List<String> apiUrls = List.of("http://example.com/api1 ", "http://example.com/api2 ");


        // 使用Vavr的Future类型来并行执行这些API调用
        CompletableFuture<Void>[] futures = apiUrls.toStream().map(url -> CompletableFuture.runAsync(() -> {
            // 模拟REST API调用
            System.out.println("Calling API: " + url);
            try {
                Thread.sleep(1000 * RandomUtil.randomInt(10)); // 模拟延时
                System.out.println("API " + url + " response received");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        })).toJavaArray(CompletableFuture[]::new);

        // 合并所有的Future对象，以便获取所有结果
        CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures);

        // 等待所有任务完成，并打印结果
        allFutures.thenAccept(f -> {
            System.out.println("All APIs have been called and responses received.");
            System.out.println(f);
        });

        AtomicBoolean complete = new AtomicBoolean(true);

        // 确保主线程不会退出，直到所有异步任务都完成
        allFutures.thenRun(() -> {
            System.out.println("Asynchronous operations completed successfully.");
            complete.set(false);
        });

        while (complete.get()) {

        }
    }

}
